package com.baidu.ocr.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.GeneralBasicParams;
import com.baidu.ocr.sdk.model.GeneralResult;
import com.baidu.ocr.sdk.model.WordSimple;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;

import java.io.File;

/**
 * Created by ccJust on 2018/1/8.
 */

public class OCRModule extends ReactContextBaseJavaModule implements ActivityEventListener {


    private static final int OCR_CAMERA_REQUEST = 111;

    private Promise ocr_camera_promise;

    private Activity activity;

    public OCRModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addActivityEventListener(this);
    }



    @Override
    public String getName() {
        return "Ocr";
    }

    @ReactMethod
    public void jumpToOcrCamera(final Promise promise) {
        ocr_camera_promise = promise;
        Activity activity = getCurrentActivity();
        Intent intent = new Intent(activity, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, getSaveFile(activity.getApplicationContext()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        activity.startActivityForResult(intent, OCR_CAMERA_REQUEST);
    }

    public File getSaveFile(Context context) {
        File file = new File(context.getFilesDir(), "pic.jpg");
        return file;
    }

    @ReactMethod
    public void ocrInit(String apiKey, String sKey, final Promise promise) {
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                Log.d("====", "onResult");
                Log.d("====", "初始化成功");
                WritableMap map = new WritableNativeMap();
                map.putBoolean("result", true);
                map.putString("token", accessToken.getAccessToken());
                promise.resolve(map);
            }

            @Override
            public void onError(OCRError ocrError) {
                Log.d("====", "onError");
                Log.d("====", ocrError.getErrorCode() + "");
                Log.d("=====", ocrError.getMessage());
                Log.d("====", "初始化失败");
                WritableMap map = new WritableNativeMap();
                map.putBoolean("result", false);
                map.putString("token", "");
                promise.resolve(map);
            }
        }, this.getCurrentActivity().getApplicationContext(), apiKey, sKey);
    }

    /**
     * @param imagePath 图片的路径
     * */
    @ReactMethod
    public void getOcrMessage(String imagePath, final Promise promise) {
        this.recognizeAccurateBasic(imagePath, promise);
    }

    private void  recognizeAccurateBasic(String imagePath, final Promise promise) {
        final GeneralBasicParams param = new GeneralBasicParams();
        param.setDetectDirection(true);
        File file1 = new File(imagePath);
        if(!file1.exists()) {
            Log.d("=====", "imageFile文件不存在");
            return;
        }
        param.setImageFile(file1);

        if(activity == null) {
            activity = getCurrentActivity();
        }

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                OCR.getInstance().recognizeAccurateBasic(param, new OnResultListener<GeneralResult>() {
                    @Override
                    public void onResult(GeneralResult generalResult) {
                        Log.d("====", "onResult");
                        Log.d("====", generalResult.getJsonRes());
                        WritableMap map = new WritableNativeMap();
                        WritableArray array = new WritableNativeArray();
                        for (WordSimple item:generalResult.getWordList()) {
                            array.pushString(item.getWords());
                        }
                        map.putString("message", "成功");
                        map.putString("json", generalResult.getJsonRes());
                        map.putInt("wordsResultNumber", generalResult.getWordsResultNumber());
                        map.putArray("wordList", array);
                        map.putBoolean("result", true);
                        map.putInt("code", 1);
                        if(promise == null) {
                            Log.d("====", "promise == null");
                            return;
                        }
                        promise.resolve(map);
                    }

                    @Override
                    public void onError(OCRError ocrError) {
                        Log.d("=====", "onError");
                        Log.d("=====", ocrError.getErrorCode() + "");
                        Log.d("=====", ocrError.getMessage());
                        WritableMap map = new WritableNativeMap();
                        map.putString("message", "失败");
                        map.putString("json", "");
                        map.putBoolean("result", false);
                        map.putInt("code", -1);
                        if(promise == null) {
                            Log.d("====", "promise == null");
                            return;
                        }
                        promise.resolve(map);
                    }
                });
            }
        });
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        Log.d("====", "onActivityResult" );
        if(resultCode == Activity.RESULT_OK) {
            if(requestCode == OCR_CAMERA_REQUEST) {
                Bundle bundle = data.getExtras();
                Log.d("====", bundle.toString());
                this.recognizeAccurateBasic(this.getSaveFile(activity.getApplication()).getAbsolutePath(), ocr_camera_promise);
            }
        } else {
            WritableMap map = new WritableNativeMap();
            map.putString("message", "取消");
            map.putString("json", "");
            map.putBoolean("result", false);
            map.putInt("code", 0);
            if(ocr_camera_promise == null) {
                Log.d("====", "promise == null");
                return;
            }
            ocr_camera_promise.resolve(map);
        }
    }

    @Override
    public void onNewIntent(Intent intent) {

    }
}
